package cn.kgc.tangcco.configurer;

import cn.kgc.tangcco.quartz.JobDemo;
import cn.kgc.tangcco.quartz.JobDemo01;
import cn.kgc.tangcco.quartz.JobDemo02;
import cn.kgc.tangcco.quartz.MyJobFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean;

/**
 * @author 李昊哲
 * @Description
 * @create 2021/1/8 11:09
 */
@Configuration
public class QuartzConfigurer {
    @Autowired
    private MyJobFactory myJobFactory;

    /**
     * 创建Job对象
     *
     * @return Job对象
     */
    @Bean
    public JobDetailFactoryBean jobDetailFactoryBean() {
        JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();
        factoryBean.setJobClass(JobDemo.class);
        return factoryBean;
    }

    /**
     * 创建Trigger对象
     *
     * @return Trigger对象
     */
    @Bean
    public SimpleTriggerFactoryBean simpleTriggerFactoryBean(JobDetailFactoryBean jobDetailFactoryBean) {
        SimpleTriggerFactoryBean factoryBean = new SimpleTriggerFactoryBean();
        factoryBean.setJobDetail(jobDetailFactoryBean.getObject());
        // 执行毫秒数
        factoryBean.setRepeatInterval(5000L);
        return factoryBean;
    }

    /**
     * 创建Trigger对象
     *
     * @return Trigger对象
     */
    @Bean
    public CronTriggerFactoryBean cronTriggerFactoryBean(JobDetailFactoryBean jobDetailFactoryBean) {
        CronTriggerFactoryBean factoryBean = new CronTriggerFactoryBean();
        factoryBean.setJobDetail(jobDetailFactoryBean().getObject());
        factoryBean.setCronExpression("0/5 * * * * ?");
        return factoryBean;
    }

    /**
     * 创建Scheduler对象
     *
     * @return Scheduler对象
     */
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(SimpleTriggerFactoryBean simpleTriggerFactoryBean, CronTriggerFactoryBean cronTriggerFactoryBean) {
        SchedulerFactoryBean factoryBean = new SchedulerFactoryBean();
        // factoryBean.setTriggers(simpleTriggerFactoryBean.getObject());
        // factoryBean.setTriggers(cronTriggerFactoryBean.getObject());
        // 延时启动
        // factoryBean.setStartupDelay(2);
        // 自定义Job Factory，用于Spring注入
        factoryBean.setJobFactory(myJobFactory);
        factoryBean.setTriggers(simpleTriggerFactoryBean.getObject(), cronTriggerFactoryBean.getObject());
        return factoryBean;
    }
}
